package com.example.text.ui.mall.view

//import androidx.activity.viewModels
//import com.alibaba.android.arouter.facade.annotation.Route
//import com.alibaba.android.arouter.launcher.ARouter
//import com.example.text.IntentData
//import com.example.text.R
//import com.example.text.base.BaseToolBarActivity
//import com.example.text.cyclone.Router
//import com.example.text.databinding.ActivityGoodsDetailBinding
//import com.example.text.ui.mall.viewmodel.MallGoodsViewModel
//import dagger.hilt.android.AndroidEntryPoint


import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.text.R
import com.example.text.base.BaseToolBarActivity
import com.example.text.databinding.ActivityGoodsDetailBinding
import com.example.text.ui.mall.viewmodel.MallGoodsViewModel



import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.example.text.IntentData
import com.example.text.app.dp
import com.example.text.cyclone.AnalyticsEventMgr
import com.example.text.cyclone.CustomIndicatorHelper
import com.example.text.cyclone.RichTextHelper
import com.example.text.cyclone.Router
import com.example.text.cyclone.Router.Ui.BookingDriverActivity
import com.example.text.cyclone.Router.Ui.CommonWebActivity
import com.example.text.cyclone.Router.Ui.EvaluationListActivity
import com.example.text.cyclone.Router.Ui.MallGroupGoodsListActivity
import com.example.text.cyclone.Router.Ui.ShoppingCarActivity
import com.example.text.databinding.ItemMallGoodsDetailBannerPicBinding
import com.example.text.dp
import com.example.text.helper.GoodsDetailServiceHelper
import com.example.text.mmkv.AuthMMKV
import com.example.text.ui.mall.adepter.CommonVDBRecyclerAdapter
import com.example.text.ui.mall.model.FormRowId
import com.example.text.ui.mall.model.GoodsFormInfoItem
import com.example.text.ui.mall.model.Info
import com.example.text.ui.mall.model.MallBanner
import com.example.text.ui.mall.model.MallGoods
import com.example.text.ui.mall.model.MallSkuItem
import com.example.text.ui.mall.viewmodel.MallDataProvider
import com.example.text.utils.ToastUtils
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.internal.platform.Platform
import kotlin.math.log

//
///**
// * Created by ZengCS on 2023/3/9.
// * E-mail:zengcs@vip.qq.com
// * Add:中国成都
// * Desc: 商品详情
// */
@AndroidEntryPoint
@Route(path = Router.Ui.GoodsDetailActivity)
class GoodsDetailActivity : BaseToolBarActivity<MallGoodsViewModel, ActivityGoodsDetailBinding>() {
    val mViewModel: MallGoodsViewModel by viewModels()
    override val mLayoutResId: Int = R.layout.activity_goods_detail

    companion object {
        fun jump(
            goodsId: Long,
            ifSeckill: Boolean = false,
            ifDou: Boolean = false,
            ifAct: Boolean = false,
            dataId: Long? = null,
            hotDataId: Long? = null
        ) {
            val navigation = ARouter.getInstance().build(Router.Ui.GoodsDetailActivity)
            navigation.withLong(IntentData.KEY_GOODS_ID, goodsId)
            navigation.withLong(IntentData.KEY_DATA_ID, dataId ?: 0L)
            navigation.withLong(IntentData.KEY_HOT_DATA_ID, hotDataId ?: 0L)
            navigation.withBoolean(IntentData.KEY_IF_SKILL, ifSeckill)
            navigation.withBoolean(IntentData.KEY_IF_ACT, ifAct)
            navigation.withBoolean(IntentData.KEY_IF_DOU, ifDou)
            navigation.navigation()
        }
    }

    @Autowired(name = IntentData.KEY_GOODS_ID)
    //@Autowired 是 Spring 框架中的一个注解，用于实现依赖注入（Dependency Injection）。
    // 它可以标注在类的成员变量、方法以及构造函数上，让 Spring 自动完成 Bean 的装配工作
    @JvmField//JvmField 是针对kotlin 字段来说的，有两重意思：
    //消除了变量的getter与setter方法
    //把变量用 public 暴露出来
    var goodsId: Long = 0L

    @Autowired(name = IntentData.KEY_DATA_ID)
    @JvmField
    var dataId: Long = 0L

    @Autowired(name = IntentData.KEY_HOT_DATA_ID)
    @JvmField
    var hotDataId: Long = 0L

    @Autowired(name = IntentData.KEY_IF_SKILL)
    @JvmField
    var ifSeckill: Boolean = false

    @Autowired(name = IntentData.KEY_IF_ACT)
    @JvmField
    var ifAct: Boolean = false

    @Autowired(name = IntentData.KEY_IF_DOU)
    @JvmField
    var ifDou: Boolean = false

    private var mGoods: MallGoods? = null
    private val bannerList = ArrayList<MallBanner>()
    private val playerMap = HashMap<Long, ExoPlayer>()

//
//    private val bottomGoodsAttributesDialog by lazy {
//        //BottomGoodsAttributesDialog()
//    }
////    private val bottomGoodsOptionsDialog by lazy {
////        BottomGoodsOptionsDialog(
////            goods = mGoods!!,
////            ifDou = ifDou,
////            onConfirm = { from ->
////                when (from) {
////                    BottomGoodsOptionsDialog.BY_CLOSE, BottomGoodsOptionsDialog.UPDATE_CHOOSE -> {
////                        // 用户切换了参数，但是没有点确定，此时只更新列表信息
////                        updateChooseInfo()
////                    }
////
////                    BottomGoodsOptionsDialog.FROM_ADD_CAR -> {
////                        addToShoppingCar()
////                    }
////
////                    BottomGoodsOptionsDialog.FROM_BUY_NOW -> {
////                        onBuyCalled()
////                    }
////
////                    BottomGoodsOptionsDialog.FROM_EXCHANGE -> {
////                        onBuyCalled()
////                    }
////                }
////            }, onBuy = {
////                onBuyCalled()
////            }, onAddCar = {
////                addToShoppingCar()
////            }
////        )
////    }
//
////    private fun onBuyCalled() {
////        if (AuthMMKV.hasLoginWithToast(this@GoodsDetailActivity)) {
////            val skuList = listOf(bottomGoodsOptionsDialog.goodsChooseOptions.skuItem!!)
////            if (ifDou) {
////                // 检查龙豆数量是否足够
////                orderPointCheck(skuList)
////            } else {
////                OrderConfirmActivity.jump(ifDou = ifDou, ifAct = ifAct, goods = mGoods, skuList = skuList, dataId = dataId)
////            }
////        }
////    }
//
//    /** C端订单-龙豆立即兑换检查 */
////    private fun orderPointCheck(skuList: List<MallSkuItem>) {
////        val orderPointCheckBody = OrderPointCheckBody()
////        orderPointCheckBody.goodsSkuDto = skuList.map {
////            GoodsSkuDtoParam(
////                goodsSkuId = it.id,
////                dataId = it.pointId,
////                number = it.count
////            )
////        }
////
////        mViewModel.orderPointCheck(orderPointCheckBody, onResult = { success, msg ->
////            setLoadingViewVisible(false)
////            if (success) {
////                DouOrderConfirmActivity.jump(goods = mGoods, skuList = skuList)
////            } else {
////                MessageNoticeDialog(
////                    message = msg,
////                    cancelable = false,
////                    onlyConfirmButton = true,
////                    confirmText = "关闭"
////                ).show(supportFragmentManager)
////            }
////        })
////    }
//
    private val mServiceHelper by lazy {
        GoodsDetailServiceHelper(mBinding.rvGoodsInfo) {
            when (it.id) {
                FormRowId.ID_GOODS_OPTIONS -> {// 选配置
                    if (mGoods == null) {
                        ToastUtils.showLong(this@GoodsDetailActivity, "数据加载中...")
                        return@GoodsDetailServiceHelper
                    }
//                    if (mGoods!!.calcRealStocks() <= 0) {
//                        return@GoodsDetailServiceHelper
//                    }

                  //  bottomGoodsOptionsDialog.updateGoods(mGoods!!)
                    if (mGoods!!.ifVehicle()) {
                        // 如果是整车，只能购买 不能加购物车
                       // bottomGoodsOptionsDialog.show(supportFragmentManager, BottomGoodsOptionsDialog.FROM_BUY_NOW)
                    } else {
//                        bottomGoodsOptionsDialog.show(
//                            supportFragmentManager,
//                            if (ifDou) BottomGoodsOptionsDialog.FROM_EXCHANGE
//                            else BottomGoodsOptionsDialog.FROM_ROW
//                        )
                    }
                }

                FormRowId.ID_GOODS_ATTRIBUTE -> {// 看参数
                    if (mGoods == null) {
                        ToastUtils.showLong(this@GoodsDetailActivity, "数据加载中...")
                        return@GoodsDetailServiceHelper
                    }
                    // bottomGoodsAttributesDialog.bindItems(MallDataProvider.mockGoodsAttributes())
//                    bottomGoodsAttributesDialog.bindItems(
//                        listOf(
//                            MallDetailInfoRow(title = "其他", info = mGoods?.params ?: "", last = true)
//                        )
//                    )
//                    bottomGoodsAttributesDialog.show(supportFragmentManager)
                }
            }
        }
    }
//    private val mRecommendHelper by lazy { GoodsDetailRecommendHelper(mBinding.rvRecommend) }
//    private val mEvaluationHelper by lazy { GoodsDetailEvaluationHelper(mBinding.rvEvaluation) }
//    private val mGoodsPicsHelper by lazy {
//        GoodsDetailPicsHelper(mBinding.mallGoodsPicContainer)
//    }
//
    override fun initView() {
        super.initView()
    ARouter.getInstance().inject(this) // 关键！必须调用
//        mBinding.ifSeckill = ifSeckill
//        mBinding.ifDou = ifDou
//        //customIndicatorHelper.moveIndicator(0)
    }

    private fun showBannerPics(ivPic: ImageView, pos: Int) {
        // 1.获取图片定位
        val pics = ArrayList<String>()
        val imageInfo = ArrayList<Info>()
        var posOffset = 0
        bannerList.forEach {
            if (it.ifVideo()) {
                posOffset = 1
            } else {
                pics.add(it.imageUrl)
                //imageInfo.add(PhotoView.getImageViewInfo(ivPic))
            }
        }
        // 2.展示图片
//        val f = PhotoViewerDialog(pics, imageInfo, pos - posOffset) {
//            val newPos = it + posOffset
//            if (mBinding.vpTop.currentItem != newPos)
//                mBinding.vpTop.setCurrentItem(newPos, false)
//        }
       // f.showDialog(supportFragmentManager)
    }

    private var intoFullVideo = false
    private fun initViewPager() {
        mBinding.vpTop.offscreenPageLimit = 3
        val mViewPagerAdapter = object : CommonVDBRecyclerAdapter<MallBanner, ItemMallGoodsDetailBannerPicBinding>(
            R.layout.item_mall_goods_detail_banner_pic, bannerList
        ) {
            override fun convert(holder: BaseDataBindingHolder<ItemMallGoodsDetailBannerPicBinding>, item: MallBanner) {
                val binding = holder.dataBinding!!
                binding.item = item
                binding.ivPic.setOnClickListener {
                    if (item.ifPic()) {
                        //showBannerPics(binding.ivPic, holder.getabsoluteAdapterPosition)
                    }
                }
                binding.playerView.setOnClickListener {
                    binding.ivPlay.visibility = View.GONE
                    val exoPlayer = playerMap[item.id]
                    if (exoPlayer?.isPlaying == true) {
                        //VideoPlayerActivity.jump(item.video)
                        intoFullVideo = true
                    } else {
                        val playbackState = exoPlayer?.playbackState
                       // JLogUtil.d("playbackState = $playbackState")
                        if (playbackState == Player.STATE_ENDED) {
                            binding.ivPlay.performClick()
                        } else {
                            exoPlayer?.play()
                        }
                    }
                }
                binding.ivPlay.setOnClickListener {
//                    it.visibility = View.GONE
//                    binding.ivPic.visibility = View.INVISIBLE
//                    val dataSourceFactory: DataSource.Factory = DefaultDataSourceFactory(
//                        this@GoodsDetailActivity, Util.getUserAgent(this@GoodsDetailActivity, "cyclone")
//                    )
//                    val proxyUrl: String = VideoCacheProxy.get()?.getProxyUrl(item.video) ?: item.video
//                    val videoSource: MediaSource =
//                        ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(
//                            MediaItem.fromUri(proxyUrl))
//
//                    var mPlayer = playerMap[item.id]
//                    if (mPlayer == null) {
//                        mPlayer = ExoPlayer.Builder(this@GoodsDetailActivity).build()
//                        playerMap[item.id] = mPlayer
//                    }
//                    mPlayer.setMediaSource(videoSource)
//                    mPlayer.prepare()
//                    binding.playerView.visibility = View.VISIBLE
//                    binding.playerView.player = mPlayer
//
//                    mPlayer.play()
//                    // 自动播放时，隐藏控制器
//                    binding.playerView.hideController()
                }

                // 视频自动播放-延时666ms
//                if (holder.absoluteAdapterPosition == 0 && mBinding.vpTop.currentItem == 0 && item.ifVideo()) {
//                    lifecycleScope.launch {
//                        delay(333)
//                        binding.ivPlay.performClick()
//                    }
//                }
                binding.executePendingBindings()
            }
        }
        mBinding.vpTop.adapter = mViewPagerAdapter
        mBinding.vpTop.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
               // pauseAllVideos()
                mBinding.tvPages.text = "${position + 1}/${bannerList.size}"
            }
        })

        // 取消滑动阴影
        val child: View = mBinding.vpTop.getChildAt(0)
        (child as? RecyclerView)?.overScrollMode = View.OVER_SCROLL_NEVER
    }

    override fun onPause() {
        super.onPause()
        //pauseAllVideos()
        /**商品详情离开浏览埋点*/
        if (mViewModel.commGoodsInfo.value == null)
            return
        AnalyticsEventMgr.getInstance().goodsBrowseExitEvent(mViewModel.commGoodsInfo.value!!, (mExitTime - mEnterTime).toString())

    }

    override fun onDestroy() {
        super.onDestroy()
        playerMap.forEach { it.value.release() }
       // recentBuyHelper.stop()
    }

    override fun initListener() {
        observeScrolled()
        initObserver()
        mBinding.tvRecommendMore.setOnClickListener {
//            MallGroupGoodsListActivity.jump(
//                forRecommend = true,
//                typeName = "为你推荐",
//                goodsId = goodsId
//            )
        }

        mBinding.ivShoppingCar.setOnClickListener {
//            if (AuthMMKV.hasLoginWithToast(this@GoodsDetailActivity)) {
//                ShoppingCarActivity.jump()
//            }
        }
        mBinding.btnJumpService.setOnClickListener {
//            if (!OnClickHelper.canClick())
//                return@setOnClickListener
//            if (AuthMMKV.hasLoginWithToast(this@GoodsDetailActivity)) {
//                mViewModel.appCAftersalesBaseGetImh5 {
//                    if (it.isNullOrEmpty()) {
//                        ToastUtils.showLong(this@GoodsDetailActivity, "在线客服连接失败")
//                        return@appCAftersalesBaseGetImh5
//                    }
//                    CommonWebActivity.jump(title = "在线客服", url = it)
//                }
//            }
        }

//        observeEvent<CreateOrderFailedEvent> {
//            // 订单创建失败，刷新数据
//            getGoodsInfo()
//        }

        mBinding.tvEvaluationMore.setOnClickListener {
           // EvaluationListActivity.jump(goodsId)
        }
        mBinding.btnAddCar.setOnClickListener {
//            bottomGoodsOptionsDialog.updateGoods(mGoods!!)
//            bottomGoodsOptionsDialog.show(supportFragmentManager, BottomGoodsOptionsDialog.FROM_ADD_CAR)
        }
        mBinding.btnBuy.setOnClickListener {
//            bottomGoodsOptionsDialog.updateGoods(mGoods!!)
//            bottomGoodsOptionsDialog.show(supportFragmentManager, BottomGoodsOptionsDialog.FROM_BUY_NOW)
        }
        mBinding.btnBuySingle.setOnClickListener {
//            bottomGoodsOptionsDialog.updateGoods(mGoods!!)
//            bottomGoodsOptionsDialog.show(supportFragmentManager, BottomGoodsOptionsDialog.FROM_BUY_NOW)
        }
        mBinding.btnExchange.setOnClickListener {
//            bottomGoodsOptionsDialog.updateGoods(mGoods!!)
//            bottomGoodsOptionsDialog.show(supportFragmentManager, BottomGoodsOptionsDialog.FROM_EXCHANGE)
        }
        mBinding.btnBooking.setOnClickListener {
//            // 预约试驾
//            if (AuthMMKV.hasLoginWithToast(this@GoodsDetailActivity)) {
//                // 预约试驾
//                mViewModel.commGoodsInfo.value?.apply {
//                    BookingDriverActivity.jump(id)
//                }
//            }
        }
        mBinding.btnSoldOut.setOnClickListener {
            ToastUtils.showLong(this@GoodsDetailActivity, "抱歉，商品已售罄")
        }

//        mBinding.btnFavorite.setOnClickListener { onFavorite() }
//        mBinding.btnFavoriteSeckill.setOnClickListener { onFavorite() }
        mBinding.floatBack.setOnClickListener { onBackPressed() }
//        mBinding.floatShare.setOnClickListener { onShare() }
//        mBinding.customToolbar.toolbarRightIcon.setOnClickListener {
//            onShare()
//        }

        //addCommonStateListener(mViewModel.stateListener)
        addCommonStateListener(mViewModel.stateListener)
    }

    private fun getGoodsInfo() {
        setLoadingViewVisible(true)
//        if (ifAct) {
//            mViewModel.mallActivityGoodsInfo(goodsId, dataId)
//        } else if (ifDou) {
            mViewModel.pointGoodsInfo(goodsId)
//        } else {
//            mViewModel.mallGoodsInfoInfo(goodsId)
//        }
    }

    override fun onLoadFailed(msg: String) {
        if (msg == "商品已下架") {
            //mBinding.customErrorUi.root.visibility = View.VISIBLE
            mBinding.customErrorUi.visibility=View.VISIBLE

           // mBinding.customErrorUi.tvErrorViewHint.text = msg
            mBinding.customErrorUi.rootView.findViewById<TextView>(R.id.tv_errorView_hint).text=msg
        }
    }

//    private val recentBuyHelper by lazy {
//        GoodsDetailRecentlyHelper2(mBinding.recentBuy)
//    }

    private fun initObserver() {
//        mViewModel.followedLiveData.observe(this) {
//            updateFavoriteState(it)
//        }
//        // 为你推荐
//        mViewModel.recommendGoodsList.observe(this) {
//            if (it.isNullOrEmpty()) {
//                mBinding.recommendContainer.visibility = View.GONE
//                return@observe
//            }
//            mBinding.recommendContainer.visibility = View.VISIBLE
//            mRecommendHelper.display(it)
//        }

//        mViewModel.shoppingCarNum.observe(this) {
//            mBinding.carNum = if (it > 99) "99" else if (it > 0) it.toString() else ""
//        }

//        mViewModel.recentlyLiveData.observe(this) {
//            // GoodsDetailRecentlyHelper(mBinding.recentBuy).convertBanner(it ?: emptyList())
//            recentBuyHelper.display(it ?: emptyList())
//        }

        mViewModel.commGoodsInfo.observe(this) {
            setLoadingViewVisible(false)
            if (it == null) {
                ToastUtils.showLong(this@GoodsDetailActivity, "商品加载失败~")
                return@observe
            }
            it.ifSeckill = ifSeckill
            it.ifDou = ifDou
            mGoods = it
//            JLogUtil.d("it.ifVehicle = ${it.ifVehicle()}")
//            JLogUtil.d("it.ifDou = ${it.ifDou}")
            //增加商品足迹
//            it.skuList?.firstOrNull()?.let {
//                mViewModel.addGoodsFootPrint(it.goodsId, it.skuImgId?.toLongOrNull())
//            }

            analysisGoodsInfo()
        }

//        //商品评论
//        mViewModel.commonEvaluatePageData.observe(this) {
//            val hasRows = !it.rows.isNullOrEmpty()
//            mBinding.tvEvaluationTitle.text = "评价${it.formatTotalRows()}"
//            mBinding.emptyEvaluate.visibility = if (hasRows) View.GONE else View.VISIBLE
//            mBinding.tvEvaluationMore.visibility = if (hasRows) View.VISIBLE else View.GONE
//            mBinding.ivMoreArrow.visibility = if (hasRows) View.VISIBLE else View.GONE
//
//            val dataList = it.rows ?: arrayListOf()
//            mEvaluationHelper.display(dataList, onImageClick = { _, child, pics, imageInfo ->
//                pauseAllVideos()
//                MallEvaluationHelper.showPicOrVideo(child, pics, imageInfo, supportFragmentManager)
//            })
//        }
    }

//    private fun onShare() {
//        val shareBody = if (ifAct) CommonShareBody(
//            id = goodsId, dataId = dataId, hotDataId = hotDataId,
//            shareType = CommonMallConstant.C_SHARE_ACTIVITY_GOODS_DETAIL
//        ) else CommonShareBody(
//            id = goodsId, shareType = if (ifDou)
//                CommonMallConstant.C_SHARE_POINT_GOODS_DETAIL
//            else CommonMallConstant.C_SHARE_GOODS_DETAIL
//        )
//
//        mViewModel.cShare(shareBody) {
//            MallGoodsShareDialog(
//                MallShareParam(
//                    h5Address = it,
//                    pic = mGoods?.mainImgUrl,
//                    name = mGoods?.title,
//                    price = mGoods?.purchasePrice ?: 0.0,
//                    marketPriceFee = (if (ifDou) mGoods?.price else mGoods?.marketPriceFee) ?: 0.0,
//                    ifDou = ifDou,
//                    point = mGoods?.point ?: ""
//                )
//            ) { platform, bitmap ->
//                when (platform) {
//                    Wechat.Name, WechatMoments.Name -> {
//                        val filePath = getExternalFilesDir(null)?.path + "/mall_share_goods.png"
//                        BitmapUtil.saveBitmap(bitmap, filePath)
//                        JShareHelper.shareImagePath(this, platform, filePath, mJShareListener)
//                    }
//
//                    SinaWeibo.Name -> {
//                        JShareHelper.shareBitmapImage(this, SinaWeibo.Name, bitmap, mJShareListener)
//                    }
//                }
//            }.show(supportFragmentManager)
//        }
//    }
//
//    private val mJShareListener: JShareListener by lazy {
//        object : JShareListener(this) {
//            override fun onComplete(p0: Platform?, p1: Int, p2: java.util.HashMap<String, Any>?) {
//                runOnUiThread {
//                    ToastUtils.showShort(this@GoodsDetailActivity, "分享成功")
//                }
//            }
//        }
//    }
//
    private fun observeScrolled() {
        val toFloat: Float = 200.toFloat()
        mBinding.nsv.setOnScrollChangeListener { _, _, scrollY, _, _ ->
            val toolbarAlpha = scrollY / toFloat
            mBinding.customToolbar.appbar.alpha = toolbarAlpha
            mBinding.customToolbar.appbar.visibility = if (toolbarAlpha > 0f) View.VISIBLE else View.INVISIBLE
            val alpha = (toFloat - if (scrollY > toFloat) toFloat else scrollY.toFloat()) / toFloat
            mBinding.floatBack.alpha = alpha
            mBinding.floatShare.alpha = alpha

            if (scrollY < toFloat) {
                mBinding.recentBuy.translationY = -scrollY.toFloat()
            }
            analysisTabLayoutOnScroll(scrollY)
        }
    }

//    private fun addToShoppingCar() {
//        if (AuthMMKV.hasLoginWithToast(this@GoodsDetailActivity)) {
//            val skuItem = bottomGoodsOptionsDialog.goodsChooseOptions.skuItem
//            val addShoppingCarBody = AddShoppingCarBody(
//                goodsId = goodsId,
//                goodsSkuId = skuItem?.id,
//                goodsSkuCode = skuItem?.goodsCode,
//                goodsSkuName = skuItem?.skuName,
//                goodsCode = mGoods?.code,
//                goodsName = mGoods?.title,
//                resourceId = skuItem?.transSkuImgId() ?: mGoods?.mainImgId ?: 0L,
//                number = bottomGoodsOptionsDialog.goodsChooseOptions.count
//            )
//            mViewModel.orderShoppingCartAdd(addShoppingCarBody)
//        }
//    }
//
//    private fun onFavorite() {
//        if (AuthMMKV.hasLoginWithToast(this@GoodsDetailActivity)) {
//            if (mBinding.tvFollowed.text == "收藏") {
//                updateFavoriteState(true)
//                mViewModel.goodsFavoriteAdd(CommonSimpleBody(id = goodsId, resourceId = mGoods?.mainImgId)) {
//                    ToastUtils.showLong(this@GoodsDetailActivity, "添加收藏失败")
//                    updateFavoriteState(false)
//                }
//            } else {
//                updateFavoriteState(false)
//                mViewModel.goodsFavoriteDetailCancel(CommonSimpleBody(id = goodsId)) {
//                    ToastUtils.showLong(this@GoodsDetailActivity, "取消收藏失败")
//                    updateFavoriteState(true)
//                }
//            }
//        }
//    }
//
//    private fun updateFavoriteState(favorite: Boolean) {
//        mBinding.ivHeart.isSelected = favorite
//        mBinding.tvFollowed.text = if (favorite) "已收藏" else "收藏"
//        mBinding.tvFollowed.isSelected = favorite
//    }
//
    override fun initData() {
        if (goodsId <= 0) {
            ToastUtils.showLong(this@GoodsDetailActivity, "商品id不能为空")
            return
        }

        getGoodsInfo()
//        // 最近下单人员列表
//        mViewModel.orderGoodsSubmitSuccess(goodsId)
//        // 为你推荐
//        if (!ifDou)
//            mViewModel.mallGoodsListRecommend(CommonPageBody(id = goodsId, limit = 8))
//        // 判断收藏状态
//        if (!ifDou)
//            mViewModel.goodsFavoriteIsFollowed(goodsId)
    }
//
    private fun pauseAllVideos() {
        playerMap.forEach { it.value.pause() }
    }

    override fun onResume() {
        super.onResume()
        // 购物车总数
        if (!ifDou)
           // mViewModel.orderShoppingCartNum()
        if (intoFullVideo) {
            lifecycleScope.launch {
                delay(100)
                val currentPos = mBinding.vpTop.currentItem
                val banner = bannerList.getOrNull(currentPos)
                if (banner?.ifVideo() == true) {
                    // 播放视频
                    playerMap[banner.id]?.play()
                }
            }
        }
        intoFullVideo = false
    }

    private fun analysisGoodsInfo() {
        mBinding.item = mGoods
        mBinding.commonPrice.item = mGoods
        mBinding.commonPrice2.item = mGoods

        bannerList.clear()
        //bannerList.addAll(MallDataProvider.makeGoodsBanners(mGoods))
       // bannerList.addAll(mViewModel.mallBannersLiveData.value)
        mBinding.withBanner = bannerList.isNotEmpty()
        initViewPager()
        // 保障信息
       mServiceHelper.display(mServiceRowItems)
        // 商品评价
      //  mViewModel.goodsEvaluateList(GoodsEvaluatingBody(limit = 2, goodsId = goodsId))
//        mEvaluationHelper.display(MallDataProvider.mockEvaluationListByCount(2), onImageClick = { _, child, pics, imageInfo ->
//            val f = PhotoViewerDialog(pics, imageInfo, child)
//            f.showDialog(supportFragmentManager)
//        })
        // 介绍图片-无

        mBinding.mallGoodsPicContainer.visibility = if (mGoods?.detailUrl.isNullOrEmpty()) View.GONE else View.VISIBLE
        if (!mGoods?.detailUrl.isNullOrEmpty()) {
            val list = arrayListOf<String>()
            list.addAll(mGoods!!.detailUrl!!)
            //mGoodsPicsHelper.display(layoutInflater, list)
        }

        // 介绍富文本
        mBinding.picsContainer.visibility = if (mGoods?.mainImgUrl.isNullOrEmpty()) View.GONE else View.VISIBLE
        Glide.with(this)
            .load(mGoods?.mainImgUrl)
            .placeholder(R.mipmap.icon_mall_placeholder) // 加载中的占位图
            .error(R.mipmap.icon_mall_placeholder)       // 加载失败的占位图
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(mBinding.img)



        RichTextHelper.displayRichText(mBinding.webView, mGoods?.details ?: "")
    }

//    private fun updateChooseInfo() {
//        mServiceRowItems[1].value = bottomGoodsOptionsDialog.goodsChooseOptions.makeInfo()
//        mServiceHelper.notifyDataSetChanged()
//    }

    private val mServiceRowItems by lazy {
        arrayListOf(
            GoodsFormInfoItem(key = "保障", value = "100%正品·售后无忧·${mGoods?.postTips()}"),
            GoodsFormInfoItem(id = FormRowId.ID_GOODS_OPTIONS, key = "已选", value = "请选择", showArrow = true),
            GoodsFormInfoItem(id = FormRowId.ID_GOODS_ATTRIBUTE, key = "参数", value = mGoods?.params ?: "商品参数", showArrow = true, last = true)
//            GoodsFormInfoItem(key = "物流", value = "48小时内发货", last = true)
        )
    }

    // 评论区可见的最小Y
    private val evaluationY0 by lazy { mBinding.evaluationContainer.top - mBinding.topPos.top }

    // 详情区可见的最小Y
    private val detailY0 by lazy { mBinding.picsContainer.top - mBinding.topPos.top }

    override fun initToolbar(toolbar: Toolbar) {
        mBinding.customToolbar.appbar.alpha = 0f
        mBinding.customToolbar.tvTab1.setOnClickListener {
            mBinding.nsv.smoothScrollTo(0, 0, 100)
            customIndicatorHelper.moveIndicator(0)
        }
        mBinding.customToolbar.tvTab2.setOnClickListener {
            mBinding.nsv.smoothScrollTo(0, evaluationY0, 100)
            customIndicatorHelper.moveIndicator(1)
        }
        mBinding.customToolbar.tvTab3.setOnClickListener {
            mBinding.nsv.smoothScrollTo(0, detailY0, 100)
            customIndicatorHelper.moveIndicator(2)
        }
    }

    private fun analysisTabLayoutOnScroll(scrollY: Int) {
        if (scrollY >= detailY0) {
            customIndicatorHelper.moveIndicator(2)
        } else if (scrollY >= evaluationY0) {
            customIndicatorHelper.moveIndicator(1)
        } else {
            customIndicatorHelper.moveIndicator(0)
        }
    }

    private val customIndicatorHelper by lazy {
        CustomIndicatorHelper(
            this@GoodsDetailActivity,
            tabList = listOf(
                mBinding.customToolbar.tvTab1,
                mBinding.customToolbar.tvTab2,
                mBinding.customToolbar.tvTab3
            ),
            indicator = mBinding.customToolbar.indicator,
            offset = 57f.dp
        )
    }
}

